import requests
import json
from operator import itemgetter
url = "https://hacker-news.firebaseio.com/v0/item/31353677.json"
r = requests.get(url)
print(f"Status code: {r.status_code}")

reponse_dict = r.json()
reponse_string = json.dumps(reponse_dict,indent = 4)
print(reponse_string)


url = "https://hacker-news.firebaseio.com/v0/topstories.json"
r = requests.get(url)
print(f"Status code: {r.status_code}")

submission_ids = r.json()
# print(submission_ids)
submission_dicts = []
for submission_id in submission_ids[:30]:
    # print(submission_id)
    url = f"https://hacker-news.firebaseio.com/v0/item/{submission_id}.json"
    r = requests.get(url, verify=False)
    print(f"id:{submission_id}\tStatus:{r.status_code}")
    response_dict = r.json()
    
    if response_dict is not None:
    # 只有当resopnse_dict不是None时，才执行下面的代码
        submission_dict = {
            'title': response_dict['title'],
            'hn_link': f"https://hacker-news.firebaseio.com/v0/item?id={submission_id}.json",
            'comment' : response_dict.get('descendants', 0),
            
        }
        # print(submission_dict)

        submission_dicts.append(submission_dict)
        
    else:
        print("获取响应数据失败，返回值为None。")
    
submission_dicts = sorted(submission_dicts,key = itemgetter('comment'),reverse = True)
for submission_dict in submission_dicts:
    print(f"\nTitle:{submission_dict["title"]}")
    print(f"hn_link:{submission_dict["hn_link"]}")
    print(f"comment:{submission_dict["comment"]}")